package alkaid.eis.schedule.component;

import java.util.List;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import alkaid.eis.schedule.core.CronTaskRegistrar;
import alkaid.eis.schedule.domain.JobInfo;
import alkaid.eis.schedule.domain.JobInfo.State;
import alkaid.eis.schedule.domain.JobInfoRepository;
import alkaid.eis.schedule.domain.JobInfoSpecifications;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 定时任务服务
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ScheduleComponent {
    private final CronTaskRegistrar cronTaskRegistrar;
    private final JobInfoRepository jobInfoRepository;

    public void start(JobInfo jobInfo) {
        if (State.STARTED.equals(jobInfo.getState())) {
            log.info("The task is already running, restart it: {}", jobInfo.toString());
        }
        if (cronTaskRegistrar.containTask(jobInfo.getId())) {
            cronTaskRegistrar.removeCronTask(jobInfo.getId());
        }
        cronTaskRegistrar.addTask(jobInfo);
    }

    public void startAll() {
        cronTaskRegistrar.destroy();

        // 默认开启的任务
        Specification<JobInfo> where = JobInfoSpecifications.enabledEqual(Boolean.TRUE);
        List<JobInfo> jobInfoList = jobInfoRepository.findAll(where);
        for (JobInfo jobInfo : jobInfoList) {
            start(jobInfo);
        }

        log.info("定时任务已加载完毕, 总共 {} 个", jobInfoList.size());        
    }

    public void shutdown(JobInfo jobInfo) {
        if (State.STOPPED.equals(jobInfo.getState())) {
            log.info("The task is already stopped: {}", jobInfo.toString());
        }

        cronTaskRegistrar.removeCronTask(jobInfo.getId());
    }

    public void shutdownAll() {
        cronTaskRegistrar.destroy();
    }
}
